const express = require('express');
const app = express();
import { render } from './render';
import routes from '../Routes';
import {getStore} from '../store/store';
import { matchRoutes } from "react-router-config";

app.use(express.static('public')); //静态资源处理

/**
 * 处理所有的访问路由
 */
app.get('*', (req, res) => {

    const store = getStore();

    // 查找匹配的路径，获取数组
    const matchedRoutes =  matchRoutes(routes, req.path);
    const promises = [];
    console.log(matchedRoutes)
    // 路由匹配，加载页面所需要的数据
    matchedRoutes.forEach((item ) => {
        if(item.route.loadData) {
            
            promises.push(item.route.loadData(store));
        }
        
    })
    Promise.all(promises).then(() => {
        res.send(render(store, routes, req));
    });
})

app.listen(3000, () => console.log('SSR app listening on port 3000!'))
